<script setup>
import layoutSlot from '@/components/layoutSlot.vue'
import outLine from '@/components/outLine.vue'
import { Plus } from '@element-plus/icons-vue'
import { userUpdateAvatarService, userGetUserInfoService } from '@/api/user.js'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

const onloadRef = ref()

import { ref } from 'vue'

const imageUrl = ref(userStore.userInfo.user_pic)

// 文件改变时的状态
const fileChange = (newFaile) => {
    // 实现本地预览
    const url = URL.createObjectURL(newFaile.raw)
    imageUrl.value = url
    // 转base64格式
    const reader = new FileReader()
    reader.readAsDataURL(newFaile.raw)
    reader.onload = () => {
        imageUrl.value = reader.result
    }
}

// 上传头像
const updateAvatar = async() => {
    const { data } = await userUpdateAvatarService(imageUrl.value)
    if (data.status === 0) {
        getUserInfo()
        ElMessage.success(data.message)
    } else {
        ElMessage.error(data.message)
    }
}

// 获取用户信息
const getUserInfo = async() => {
    const { data } = await userGetUserInfoService()
    userStore.setUserInfo(data.data)
}
</script>

<template>
    <div class="contact">
        <layoutSlot>
            <template #title>更换头像</template>
            <template #main>
                <outLine></outLine>
               <div class="upload-btn">
                <el-upload
                    ref="onloadRef"
                    class="avatar-uploader"
                    :show-file-list="false"
                    :on-change="fileChange">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="avatar-uploader-icon"><el-icon><Plus /></el-icon></i>
                </el-upload>
                <div class="btn">
                    <el-button type="primary" @click="onloadRef.$el.querySelector('input').click()">选择图片</el-button>
                    <el-button type="success" @click="updateAvatar">上传头像</el-button>
                </div>
               </div>
            </template>
        </layoutSlot>
    </div>
</template>

<style scoped lang="scss">
.upload-btn {
    width: 200px;
    .btn {
        display: flex;
        margin-top: 20px;
        justify-content: space-between;
    }
}
  .avatar-uploader-icon {
    border: 1px dashed black;
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  .avatar-uploader .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar {
    width: 200px;
    height: 200px;
    display: block;
  }
</style>